package com.cloudptt.wp.ui.views;

import android.content.Context;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.cloudptt.wp.R;
import com.cloudptt.wp.ui.views.listener.BraceSpaceListener;

/**
 * on 2017/7/19.
 * 类的描述:
 */

public class ClearEditText extends LinearLayout implements View.OnClickListener {
	/**
	 * 删除按钮的引用
	 */
	private EditText editText = null;
	private ImageButton delBtn = null;

	private BraceSpaceListener braceSpace = null;
	/**
	 * 控件是否有焦点
	 */
	private boolean hasFoucs;
	public ClearEditText(Context context) {
		this(context, null);
	}

	public ClearEditText(Context context, AttributeSet attrs) {
		//这里构造方法也很重要，不加这个很多属性不能再XML里面定义
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		init(context);
	}

	public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);

		init(context);
	}
	private void init(Context context)
	{
		LayoutInflater.from(context).inflate(R.layout.layout_edit_del, this);
		editText = (EditText)findViewById(R.id.editText);

		editText.setInputType(InputType.TYPE_NULL);
//		editText.requestFocus();
//		editText.setFocusable(true);
		editText.setCursorVisible(true);

		LinearLayout delLy = (LinearLayout)findViewById(R.id.delLy);
		delLy.setOnClickListener(this);
		delBtn = (ImageButton)findViewById(R.id.delBtn);
		delBtn.setOnClickListener(this);
		setClearIconVisible(editText.getText().length() > 0);
	}

	public void setBraceSpaceListener(BraceSpaceListener braceSpace)
	{
		this.braceSpace = braceSpace;
	}

	public void setText(String str)
	{
		this.editText.setText(str);
		editText.setSelection(str.length());
		setClearIconVisible(editText.getText().length() > 0);
	}
	public String getText()
	{
		return editText.getText().toString();
	}

	/**
	 * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
	 * @param visible
	 */
	public void setClearIconVisible(boolean visible) {
		if(visible) {
			this.delBtn.setVisibility(View.VISIBLE);
		}
		else {
			this.delBtn.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		if(R.id.delBtn == v.getId()
			|| R.id.delLy == v.getId()){
			if(braceSpace != null)
			{
				braceSpace.brackSpace();
			}
			setClearIconVisible(editText.getText().length() > 0);
		}
	}
}
